package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.DestroyRoleInfo;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注销
 */
public class DestroyRoleDaoImpl extends TempDataObjectDao<DestroyRoleInfo> {

	public Map<Long, DestroyRoleInfo> getDestroyRoleInfoMap() {
		ResultSet rs = null;
		CallableStatement call = null;
		Map<Long, DestroyRoleInfo> dataMap = new ConcurrentHashMap<>();
		String sql = "select * from t_u_destroy_role where status<2";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			rs = call.executeQuery();
			while (rs.next()) {
				DestroyRoleInfo data = parse(rs);
				dataMap.put(data.getUserId(), data);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return dataMap;
	}

	@Override
	protected boolean addData(DestroyRoleInfo data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_destroy_role(userId,status,destroyTime) VALUES(?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setLong(i++, data.getStatus());
			call.setLong(i++, data.getDestroyTime());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(DestroyRoleInfo data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_destroy_role SET status=?,destroyTime=? WHERE userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setInt(i++, data.getStatus());
			call.setLong(i++,data.getDestroyTime());
			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected DestroyRoleInfo parseData(ResultSet rs) throws SQLException {
		DestroyRoleInfo data = new DestroyRoleInfo();
		data.setUserId(rs.getLong("userId"));
		data.setStatus(rs.getInt("status"));
		data.setDestroyTime(rs.getLong("destroyTime"));
		return data;
	}
}
